import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { StreamServer, Device } from '@/types'
import { $getAllServer, $getCameraListByNvrId, $addServer, $editServer, $deleteServer, $getStreamPreviewPort,$refreshDeviceListByServerId } from '@/api/nvr'
import { getCameraTree } from '@/api/camera'
import { deleteMenu, moveCamerasToGroup as moveCamerasToGroupAPI } from '@/api/device'
import { buildStreamUrl as buildStreamUrlUtil } from '@/utils/streamUrl'

export const useStreamStore = defineStore('stream', () => {
  // 状态
  const streamServers = ref<StreamServer[]>([])
  const cameraList = ref<Device[]>([])
  const selectedServer = ref<StreamServer | { id: 'all' } | null>(null)
  const selectedCameras = ref<number[]>([])
  const loading = ref(false)
  const cameraLoading = ref(false)
  
  // 分页状态
  const cameraPageConfig = ref({
    currentPage: 1,
    pageSize: 20,
    total: 0,
    pageSizes: [10, 20, 50, 100],
    layout: 'total, sizes, prev, pager, next, jumper',
    background: true,
    disabled: false,
    small: false
  })

  // 分组数据
  const groupList = ref([
    {
      id: 1,
      name: '钢厂区域目录1',
      expanded: true,
      cameras: [
        { id: 1, name: '卷包车间电梯口半球', ip: '10.96.216.9', checked: false },
        { id: 2, name: '成品高架库三楼A9', ip: '10.96.216.41', checked: false }
      ]
    },
    {
      id: 2,
      name: '钢厂区域目录2',
      expanded: false,
      cameras: []
    },
    {
      id: 3,
      name: '钢厂区域目录3',
      expanded: true,
      cameras: [
        { id: 3, name: '质量监督站入口', ip: '10.96.216.52', checked: false },
        { id: 4, name: '危化品库半球1', ip: '10.96.216.54', checked: false }
      ]
    }
  ])

  const selectedGroup = ref<any>(null)

  // 计算属性
  const hasSelectedCameras = computed(() => selectedCameras.value.length > 0)
  const hasSelectedServer = computed(() => !!(selectedServer.value && selectedServer.value.id !== 'all'))
  const hasSelectedGroup = computed(() => !!selectedGroup.value)

  // 获取流媒体服务器列表
  const loadStreamServers = async (): Promise<void> => {
    try {
      loading.value = true
      const response = await $getAllServer()
      console.log('getAllServer response:', response)
      const streamPortResponse = await $getStreamPreviewPort()
      console.log('getStreamPreviewPort response:', streamPortResponse)
      await getCameraTree()

      // 根据实际API返回结构调整
      if (response.data && Array.isArray(response.data)) {
        streamServers.value = response.data.map(server => ({ ...server, streamPort: parseInt(streamPortResponse.data.realStreamPort) }))
        // 默认选择第一个服务器
        if (streamServers.value.length > 0) {
          selectedServer.value = streamServers.value[0]
          if (streamServers.value[0].id) {
            await loadCameraList(streamServers.value[0].id)
          }
        }
      }
    } finally {
      loading.value = false
    }
  }
  // 构建流地址
  const buildStreamUrl = (device: Device, streamType: 'flv' | 'flvsub' | 'hls' | 'hlssub'): string => {
    return buildStreamUrlUtil(device, streamServers.value, streamType)
  }
  // 获取摄像机列表
  const loadCameraList = async (nvrId: string | number, page: number = 1, pageSize: number = 20, keyword: string = ''): Promise<void> => {
    try {
      cameraLoading.value = true
      const params = {
        nvrId: Number(nvrId),
        page,
        pageSize,
        keyword
      }
      const response = await $getCameraListByNvrId(params)
      if (response.data && response.data.data) {
        cameraList.value = response.data.data as unknown as Device[]
        cameraPageConfig.value.total = response.data.total || 0
        cameraPageConfig.value.currentPage = page
        cameraPageConfig.value.pageSize = pageSize
      } else {
        cameraList.value = []
        cameraPageConfig.value.total = 0
      }
    }  finally {
      cameraLoading.value = false
    }
  }
  // 刷新NVR下的设备
  const refreshDeviceListByServerId = async (serverId: number): Promise<void> => {
    await $refreshDeviceListByServerId(serverId)
  }

  // 选择服务器
  const selectServer = async (server: StreamServer | { id: 'all' }): Promise<void> => {
    selectedServer.value = server
    if (server.id !== 'all' && server.id) {
      await loadCameraList(server.id)
    } else {
      // 如果选择"所有流媒体"，清空摄像机列表
      await loadCameraList(-1)
    }
  }

  // 刷新摄像机列表
  const refreshCameraList = async (): Promise<void> => {
    if (selectedServer.value && selectedServer.value.id !== 'all' && selectedServer.value.id) {
      await loadCameraList(
        selectedServer.value.id,
        cameraPageConfig.value.currentPage,
        cameraPageConfig.value.pageSize
      )
    }
  }

  // 分页大小改变
  const handleCameraPageSizeChange = async (pageSize: number, keyword: string = ''): Promise<void> => {
    cameraPageConfig.value.pageSize = pageSize
    cameraPageConfig.value.currentPage = 1
    if (selectedServer.value && selectedServer.value.id !== 'all' && selectedServer.value.id) {
      await loadCameraList(selectedServer.value.id, 1, pageSize, keyword)
    }
  }

  // 当前页改变
  const handleCameraCurrentPageChange = async (currentPage: number, keyword: string = ''): Promise<void> => {
    cameraPageConfig.value.currentPage = currentPage
    if (selectedServer.value && selectedServer.value.id !== 'all' && selectedServer.value.id) {
      await loadCameraList(
        selectedServer.value.id,
        currentPage,
        cameraPageConfig.value.pageSize,
        keyword
      )
    }
  }

  // 切换摄像机选择
  const toggleCameraSelection = (cameraId: number): void => {
    const index = selectedCameras.value.indexOf(cameraId)
    if (index > -1) {
      selectedCameras.value.splice(index, 1)
    } else {
      selectedCameras.value.push(cameraId)
    }
  }

  // 清空摄像机选择
  const clearCameraSelection = (): void => {
    selectedCameras.value = []
  }

  // 选择分组
  const selectGroup = (group: any): void => {
    selectedGroup.value = group
    group.expanded = !group.expanded
  }

  // 添加流媒体服务器
  const addStreamServer = async (serverData: Partial<StreamServer>): Promise<void> => {
    try {
      const response = await $addServer(serverData as StreamServer)
      console.log('addServer response:', response)
      streamServers.value.push(response.data)
    } catch (error) {
      console.error('添加服务器失败:', error)
      throw error
    }
  }

  // 更新流媒体服务器
  const updateStreamServer = async (serverData: StreamServer): Promise<void> => {
    try {
      const response = await $editServer(serverData.id ?? 0,serverData.name ?? '')
      console.log('editServer response:', response)
      // 更新本地数据
      const index = streamServers.value.findIndex(s => s.id === serverData.id)
      if (index > -1) {
        streamServers.value[index] = { ...streamServers.value[index], ...serverData }
      }
    } catch (error) {
      console.error('更新服务器失败:', error)
      throw error
    }
  }

  // 删除流媒体服务器
  const deleteStreamServer = async (serverId: number): Promise<void> => {
    try {
      const response = await $deleteServer(serverId)
      console.log('deleteServer response:', response)
      
      // 从本地列表中移除
      const index = streamServers.value.findIndex(s => s.id === serverId)
      if (index > -1) {
        streamServers.value.splice(index, 1)
      }
    } catch (error) {
      console.error('删除服务器失败:', error)
      throw error
    }
  }

  // 添加分组
  const addGroup = async (groupData: { name: string }): Promise<void> => {
    const newGroup = {
      id: Date.now(),
      name: groupData.name,
      expanded: false,
      cameras: []
    }
    groupList.value.push(newGroup)
  }

  // 更新分组
  const updateGroup = async (groupData: { id: number; name: string }): Promise<void> => {
    const group = groupList.value.find(g => g.id === groupData.id)
    if (group) {
      group.name = groupData.name
    }
  }

  // 删除分组
  const deleteGroup = async (groupId: number): Promise<void> => {
    try {
      // 调用删除菜单API
      await deleteMenu(groupId)
      
      // 从本地列表中移除
      const index = groupList.value.findIndex(g => g.id === groupId)
      if (index > -1) {
        groupList.value.splice(index, 1)
      }
    } catch (error) {
      console.error('删除分组失败:', error)
      throw error
    }
  }

  // 移动摄像机到分组
  const moveCamerasToGroup = async (cameraIds: number[], groupId: number): Promise<void> => {
    try {
      // 调用API移动摄像机到分组
      await moveCamerasToGroupAPI(cameraIds, groupId)
    } catch (error) {
      console.error('移动摄像机到分组失败:', error)
      throw error
    }
  }

  return {
    // 状态
    streamServers,
    cameraList,
    selectedServer,
    selectedCameras,
    selectedGroup,
    groupList,
    loading,
    cameraLoading,
    cameraPageConfig,

    // 计算属性
    hasSelectedCameras,
    hasSelectedServer,
    hasSelectedGroup,

    // 方法
    loadStreamServers,
    loadCameraList,
    selectServer,
    refreshCameraList,
    refreshDeviceListByServerId,
    handleCameraPageSizeChange,
    handleCameraCurrentPageChange,
    toggleCameraSelection,
    clearCameraSelection,
    selectGroup,
    addStreamServer,
    updateStreamServer,
    deleteStreamServer,
    addGroup,
    updateGroup,
    deleteGroup,
    moveCamerasToGroup,
    buildStreamUrl
  }
})
